<template>
  <div class="page-login">
    <div class="login-left">
      
    </div>
    <div class="login-right">
		<div class="logo">
		  <img v-lazy="web_info.COMPANY_LOGO" :key="web_info.COMPANY_LOGO"/>
		</div>
      <div class="login-box" v-show="pageType === 'login'">
        <div class="nav-bar">
          <div :class="['nav-item',navBarActive == 1?'active':'']" @click="navBarHandle(1)">账号密码登录</div>
          <div :class="['nav-item',navBarActive == 2?'active':'']" @click="navBarHandle(2)">邮箱登录</div>
        </div>
        <div class="phone" v-show="navBarActive == 1">

          <Form ref="form1" :model="param" :rules="login_rules" inline>

            <FormItem prop="username" style="width:100%;" class="content-phone">
              <div class="username">
                <span>账号 |</span>
              </div>
              <Input type="text" v-model="param.username" style="" placeholder="请输入账号" />
            </FormItem>
            <FormItem prop="password" style="width:100%;" class="content-phone">
              <div class="username">
                <span>密码 |</span>
              </div>
              <Input type="password" v-model="param.password" placeholder="请输入密码" />
            </FormItem>
          </Form>

        </div>
        <div class="email" v-show="navBarActive == 2">
          <Form ref="form2" :model="param1" :rules="login_rules1" inline>

            <FormItem prop="username" style="width:100%;" class="content-phone">
              <div class="username">
                <span>邮箱 |</span>
              </div>
              <Input type="text" v-model="param1.username" style="" placeholder="请输入邮箱" />
            </FormItem>
            <FormItem prop="password" style="width:100%;" class="content-phone">
              <div class="username">
                <span>密码 |</span>
              </div>
              <Input type="password" v-model="param1.password" placeholder="请输入密码" />
            </FormItem>
          </Form>
        </div>
        <Button class="submit-btn" type="primary" @click="onSubmit">登录</Button>
        <div class="login-footer">
          <div class="footer-left">
            <nuxt-link to="/regist">账号注册</nuxt-link>
          </div>
          <div class="footer-right" @click="forgetPwdHandle('forget')">忘记密码</div>
        </div>
        <div class="quick-login" v-if="third_part_login.open == true">快捷登录</div>
        <div class="weixin" v-if="third_part_login.open == true">
          <img src="/img/pc/login-weixin.png" alt="" @click="wachatLogin">
        </div>
        <div class="tohome" @click="$router.push('/')">
          <Icon type="ios-arrow-back" size="13" /><span>回到首页</span>
        </div>
      </div>
      <div class="forget-pwd" v-show="pageType === 'forget'">
        <div class="forget-title">忘记密码</div>
        <div class="forget-box" v-show="web_info.VERIFY_TYPE == 1">
          <Form ref="forget-form" :model="forgetPwdParam" :rules="forgetPwdRules" inline :label-width="90">

            <FormItem prop="username" style="width:100%;" class="content-forget" label="账号：">
              <Input type="text" v-model="forgetPwdParam.username" style="" placeholder="请输入账号" />
            </FormItem>
            <FormItem prop="password" style="width:100%;" class="content-forget" label="新密码：">
              <Input type="password" v-model="forgetPwdParam.password" placeholder="请输入新密码" />
            </FormItem>
            <FormItem prop="mobile" style="width:100%;" class="content-forget" label="手机号：">
              <Input type="text" v-model="forgetPwdParam.mobile" style="" placeholder="请输入手机号" />
            </FormItem>
            <FormItem prop="code" style="width:100%;" class="content-forget" label="验证码：">
              <Row>
                <Col span="13">
                <Input type="text" v-model="forgetPwdParam.code" style="" placeholder="请输入验证码" />
                </Col>
                <Col span="9" offset="1">
                <Button type="primary" @click="getCode('mobile')" :disabled="isSend">
                  <span v-if="!isSend">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;发送&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                  <span v-else>已发送({{seconds}})</span>
                </Button>
                </Col>
              </Row>
            </FormItem>
          </Form>
        </div>
        <div class="forget-box" v-show="web_info.VERIFY_TYPE == 0">
          <Form ref="forget-form1" :model="forgetPwdParam1" :rules="forgetPwdRules1" inline :label-width="90">
            <FormItem prop="username" style="width:100%;" class="content-forget" label="账号：">
              <Input type="text" v-model="forgetPwdParam1.username" style="" placeholder="请输入账号" />
            </FormItem>
            <FormItem prop="password" style="width:100%;" class="content-forget" label="新密码：">
              <Input type="password" v-model="forgetPwdParam1.password" placeholder="请输入新密码" />
            </FormItem>
            <FormItem prop="email" style="width:100%;" class="content-forget" label="邮箱：">
              <Input type="text" v-model="forgetPwdParam1.email" style="" placeholder="请输入邮箱" />
            </FormItem>
            <FormItem prop="code" style="width:100%;" class="content-forget" label="验证码：">
              <Row>
                <Col span="13">
                  <Input type="text" v-model="forgetPwdParam1.code" style="" placeholder="请输入验证码" />
                </Col>
                <Col span="9" offset="1">
                  <Button type="primary" @click="getCode('email')" :disabled="isSend">
                    <span v-if="!isSend">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;发送&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <span v-else>已发送({{seconds}})</span>
                  </Button>
                </Col>
              </Row>
            </FormItem>
          </Form>
        </div>
        <Button class="submit-btn" type="primary" @click="updatePwdHandle()">提交</Button>
        <div class="login-footer">
          <div class="footer-left" @click="forgetPwdHandle('login')">回到登录</div>
        </div>
      </div>
    </div>
    <van-dialog v-model="is_show_modal" @cancel="is_show_modal = false" :title="$t('locale.pc.login.t16')" @close="is_show_modal = false" show-cancel-button :show-confirm-button="false">
      <verify-slider ref="verify_slider" style="width:100%;margin:20px 0 0 0" @success="handleSuccess"></verify-slider>
    </van-dialog>
  </div>
</template>
<script>
import { mapMutations, mapState, mapActions } from "vuex";
import { userLogin, wxQrLogin } from "~/api/account/user.js";
import {
  userInfoUpdate,
  uploadAvatar,
  updatePass,
  getEmailCode,
  unbindWechat,
  getSmsCode,
  getVerifyCode,
  updateUserPwd,
  resetPass
} from "~/api/account/user.js";
import { strToHexCharCode, hexCharCodeToStr } from "~/utils/commonfun";
import { setInClient } from "~/utils/cookies.js";
import VerifySlider from "~/components/vue-verify-slider.vue";
export default {
  components: { VerifySlider },
  data() {
    return {
      seconds: 0, //倒计时
      isSend: false,
      pageType: "login",
      navBarActive: 1,
      respond_code: new RegExp(""), //验证码
      is_show_modal: false,
      login_rules: {
        username: [
          {
            required: true,
            message: this.$t("locale.pc.login.t17"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("locale.pc.login.t18"),
            trigger: "blur",
          },
        ],
      },
      login_rules1: {
        username: [
          {
            required: true,
            message: this.$t("locale.pc.login.t19"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("locale.pc.login.t20"),
            trigger: "blur",
          },
        ],
      },
      param: {
        username: "",
        password: "",
      },
      param1: {
        username: "",
        password: "",
      },
      forgetPwdParam: {
        username: "",
        mobile: "",
        code: "",
        password: "",
      },
      forgetPwdParam1: {
        username: "",
        email: "",
        code: "",
        password: "",
      },
      forgetPwdRules: {
        username: [
          {
            required: true,
            message: "账号不能为空",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "手机不能为空" },
          {
            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
            message: "手机号不正确",
          },
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur",
          },
          {
            pattern: this.respond_code,
            message: "验证码不正确",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
        ],
      },
      forgetPwdRules1: {
        username: [
          {
            required: true,
            message: "账号不能为空",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "邮箱不能为空" },
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: "邮箱格式不正确",
          },
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur",
          },
          {
            pattern: this.respond_code,
            message: "验证码不正确",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
        ],
      },
      actived_tap: "key1",
      rememberme: false,
      flagCode: false,
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      third_part_login(state) {
        return state.third_part_login;
      },
      web_info(state) {
        return state.web_info;
      },
    }),
  },
  watch: {},
  methods: {
    ...mapActions(["initBuyRecord", "initBuyCourseRecord","initSignAgreement","initSignInCourse","initRtcInfo","getMineV2QuestionBankList"]),
    ...mapMutations([
      "SET_IS_LOADING",
      "SET_TOKEN",
      "SET_USERINFO",
      "SET_LOGINTYPE",
    ]),
    cuntDown() {
      this.interval = setInterval(() => {
        this.seconds--;
        if (this.seconds <= 0) {
          this.seconds = 0;
          this.isSend = false;
          clearInterval(this.interval);
        }
      }, 1000);
    },
    getCode(type) {
      console.log(type);
      if (type === "mobile") {
        this.$refs["forget-form"].validateField("username", (valid_err) => {
          if (!valid_err) {
            this.$refs["forget-form"].validateField("password", (valid_err) => {
              if (!valid_err) {
                this.$refs["forget-form"].validateField("mobile", async (valid_err) => {
                  if (!valid_err) {
                    // 表单验证通过
                    console.log("验证通过");
                    let param = {
                      account:this.forgetPwdParam.username,
                      mobile: this.forgetPwdParam.mobile,
                    };
                    if(this.flagCode){
                      return false;
                    }
                    this.flagCode = true;
                    let result = await getVerifyCode(param);
                    if (result && result.data && result.data.code == 200) {
                          this.isSend = true;
                          this.flagCode = false;
                          this.seconds = 60;
                          this.cuntDown();
                    }else if(result && result.data && result.data.code == 1){
                      this.$Message.error(res.data.msg);
                    }else if(result && result.data && result.data.code == 2){
                      this.$Message.error(res.data.msg);
                    }else{
                      this.$Message.error("发送失败");
                    }
                  }
                });
              }
            });
          }
        });
      } else if (type === "email") {
        console.log(this.forgetPwdParam1);
        this.$refs["forget-form1"].validateField("username", (err) => {
          if (!err) {
            this.$refs["forget-form1"].validateField("password", (err) => {
              if (!err) {
                this.$refs["forget-form1"].validateField("email", async (err) => {
                  if (!err) {
                    let param = {
                      account:this.forgetPwdParam1.username,
                      email: this.forgetPwdParam1.email,
                    };
                    if(this.flagCode){
                      return false;
                    }
                    this.flagCode = true;
                    let result = await getVerifyCode(param);
                    if (result && result.data && result.data.code == 200) {
                          this.isSend = true;
                          this.flagCode = false;
                          this.seconds = 60;
                          this.cuntDown();
                    }else if(result && result.data && result.data.code == 1){
                      this.$Message.error(res.data.msg);
                    }else if(result && result.data && result.data.code == 2){
                      this.$Message.error(res.data.msg);
                    }else{
                      this.$Message.error("发送失败");
                    }
                  }
                });
              }
            });
          } else {
            console.log("验证失败");
          }
        });
      }
    },
    updatePwdHandle() {
      if (this.web_info.VERIFY_TYPE == 0) {
        this.$refs["forget-form1"].validate(async (valid) => {
          if (valid) {
            let params = {
              account:this.forgetPwdParam1.username,
              code:this.forgetPwdParam1.code,
              newPwd:this.forgetPwdParam1.password,
            };
            console.log("邮箱验证", params);
            let result = await updateUserPwd(params);
            if (result && result.data && result.data.code == 200) {
                  this.$Message.success('修改密码成功！');
                  this.forgetPwdHandle('login')
            }else if(result && result.data && result.data.code == 1){
              this.$Message.error(res.data.msg);
            }else{
              this.$Message.error("修改密码失败！");
            }
          } else {
            // this.$Message.error("Fail!");
          }
        });
      } else if (this.web_info.VERIFY_TYPE == 1) {
        this.$refs["forget-form"].validate(async (valid) => {
          if (valid) {
            let params = {
              account:this.forgetPwdParam.username,
              code:this.forgetPwdParam.code,
              newPwd:this.forgetPwdParam.password,
            };
            console.log("手机验证", params);
            let result = await updateUserPwd(params);
            if (result && result.data && result.data.code == 200) {
                  this.$Message.success('修改密码成功！');
                  this.forgetPwdHandle('login')
            }else if(result && result.data && result.data.code == 1){
              this.$Message.error(result.data.msg);
            }else{
              this.$Message.error("修改密码失败！");
            }
          } else {
            // this.$Message.error("Fail!");
          }
        });
      }
    },
    validateMobile(val) {
      return !new RegExp("^" + this.user_info.mobile + "$").test(
        val.replace(/ /g, "")
      );
    },
    validateEmail(val) {
      return !new RegExp("^" + this.user_info.email + "$").test(
        val.replace(/ /g, "")
      );
    },
    forgetPwdHandle(type) {
      this.pageType = type;
    },
    navBarHandle(type) {
      this.navBarActive = type;
    },
    onSubmit() {
      let name = "form1";
      if (this.navBarActive === 1) {
        name = "form1";
      } else {
        name = "form2";
      }
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          this.is_show_modal = true;
        } else {
          // this.$Message.error("Fail!");
        }
      });
    },
    async handleSuccess() {
      let email_reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      let phone_reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      let login_type = "";
      let params;
      if (this.navBarActive == 1) {
        params = {
          password: this.param.password,
          rememberme: this.rememberme,
        };
        if (email_reg.test(this.param.username)) {
          params = {
            ...params,
            email: this.param.username
          };
          login_type = "email";
        } else if (phone_reg.test(this.param.username)) {
          params = {
            ...params,
            account: this.param.username
          };
          login_type = "mobile";
        } else {
          params = {
            ...params,
            account: this.param.username
          };
          login_type = "account";
        }
      } else {
        params = {
          password: this.param1.password,
          rememberme: this.rememberme
        };
        if (email_reg.test(this.param1.username)) {
          params = {
            ...params,
            email: this.param1.username
          };
          login_type = "email";
        } else if (phone_reg.test(this.param1.username)) {
          params = {
            ...params,
            account: this.param1.username
          };
          login_type = "mobile";
        } else {
          params = {
            ...params,
            account: this.param1.username
          };
          login_type = "account";
        }
      }
      console.log("params:", params);
      this.is_show_modal = false;
      this.SET_IS_LOADING(true);
      let result = await userLogin(params);
      if (result && result.data && result.data.code === 200) {
        this.SET_TOKEN(result.headers.authorization);
        this.SET_USERINFO(result.data.data, this.rememberme);
        this.SET_LOGINTYPE(login_type);
        this.$Message.success(this.$t("locale.pc.login.t21"));
        this.initBuyRecord();
        this.initRtcInfo();
        this.initBuyCourseRecord();
        this.initSignAgreement();
        this.initSignInCourse();
        this.getMineV2QuestionBankList();
        this.$router.push("/");
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        const { verify_slider } = this.$refs;
        console.log("verify_slider:", verify_slider);
        verify_slider.initComponent.call(verify_slider);
        verify_slider.initConfig.call(verify_slider);
        verify_slider.mouseMoveStatus = false;
        this.$Message.warning({
            content: result.data.msg,
            duration: 3
        });
      }
    },
    async wachatLogin() {
      this.SET_IS_LOADING(true);
      let result = await wxQrLogin(1);
      console.log("result:", result);
      if (result && result.data.code === 200) {
        // console.log(result.data.data);
        window.open(result.data.data.oauthUrl);
      } else {
        this.$Message.error(this.$t("locale.pc.login.t24"));
      }
    },
  },
  created() {
    if (process.client) {
      if (this.token && Object.keys(this.user_info).length > 0) {
        this.$router.replace("/");
      }
    }
  },
  mounted() {},
};
</script>
<style lang="scss">
.page-login {
  background: white;
  width: 100%;
  min-height: 100vh;
  display: flex;
  .login-left,.login-right{
    min-height: 100vh;
    width: 50%;
  }
  .login-left{
    background-image: url("/img/pc/login-bg1.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    position: relative;
    
  }

  .login-right {
	background-image: url("/img/pc/login-bg2.jpg");
	background-repeat: no-repeat;
	background-size: 100% 100%;
    position: relative;
	.logo{
	  // position: absolute;
	  // left: 40px;
	  // top: 40px;
	  width: 302px;
	  height: 60px;
	  margin: 100px auto 0px;
	  img{
	    width: 100%;
	    height: 100%;
	    display: block;
	  }
	}
    .forget-pwd {
      position: absolute;
      top: 0;
      bottom: 0;
      // right: 40px;
      left: 0;
      right: 0;
      // right: 10%;
      margin: auto;
      width: 360px;
      height: 360px;
      .forget-title {
        font-size: 16px;
        font-weight: bold;
        color: #41454d;
        text-align: center;
      }
      .forget-box {
        margin-top: 20px;
        .ivu-input {
          height: 40px;
          border-radius: 4px;
          padding: 4px 0px 4px 6px;
          font-size: 16px;
        }
        .ivu-form-item-error-tip {
          padding-left: 0px;
        }
        .ivu-form .ivu-form-item-label {
          font-size: 16px;
          // line-height: 40px;
          line-height: 20px;
        }
        .content-forget {
          position: relative;
          .ivu-btn {
            font-size: 16px;
          }
          .name {
            position: absolute;
            z-index: 999;
            left: 10px;
            top: 0;
            display: flex;
            line-height: 40px;
            img {
              display: block;
              background: var(--theme-color);
            }
            span {
              color: #88909f;
              font-size: 16px;
            }
          }
        }
      }
      .submit-btn {
        margin-top: 10px;
        width: 100%;
        height: 45px;
        border-radius: 20px;
        font-size: 16px;
      }
      .login-footer {
        padding: 10px 10px;
        display: flex;
        justify-content: space-between;
        .footer-left {
          cursor: pointer;
        }
        .footer-left:hover {
          color: var(--theme-color);
          text-decoration: underline;
        }
        .footer-right {
          cursor: pointer;
        }
        .footer-right:hover {
          text-decoration: underline;
          color: var(--theme-color);
        }
      }
    }
    .login-box {
      position: absolute;
      top: 0;
      bottom: 0;
      // right: 60px;
      left: 0;
      right: 0;
      margin: auto;
      width: 300px;
      height: 360px;
      // background-color: red;
      .nav-bar {
        display: flex;
        justify-content: space-around;
        font-size: 16px;
        font-weight: bold;

        .nav-item {
          cursor: pointer;
          color: #a4adbd;
        }
        .nav-item.active {
          color: #41454d;
          position: relative;
        }
        .nav-item.active::before {
          width: 100%;
          content: "";
          display: block;
          height: 3px;
          position: absolute;
          left: 0;
          bottom: -5px;
          border-radius: 2px;
          background: var(--theme-color);
        }
      }
      .submit-btn {
        margin-top: 10px;
        width: 100%;
        height: 45px;
        border-radius: 20px;
        font-size: 16px;
      }
      .login-footer {
        padding: 10px 10px;
        display: flex;
        justify-content: space-between;
        .footer-left {
          cursor: pointer;
        }
        .footer-left:hover {
          color: var(--theme-color);
          text-decoration: underline;
        }
        .footer-right {
          cursor: pointer;
        }
        .footer-right:hover {
          text-decoration: underline;
          color: var(--theme-color);
        }
      }
      .quick-login {
        width: 100%;
        text-align: center;
        line-height: 30px;
        position: relative;
        &::before {
          position: absolute;
          content: "";
          display: block;
          left: 0;
          top: 14px;
          width: 110px;
          height: 2px;
          background-color: #e3e5e9;
        }
        &::after {
          position: absolute;
          content: "";
          display: block;
          right: 0;
          top: 14px;
          width: 110px;
          height: 2px;
          background-color: #e3e5e9;
        }
      }
      .weixin {
        width: 100%;
        margin-top: 20px;
        img {
          display: block;
          width: 40px;
          height: 40px;
          margin: 0 auto;
          border-radius: 50%;
          overflow: hidden;
          cursor: pointer;
        }
      }
      .tohome {
        display: flex;
        align-items: center;
        cursor: pointer;
        margin: 20px 0;
        width: 66px;
      }
      .tohome:hover {
        color: var(--theme-color);
      }
      .phone {
        padding: 40px 0 0 0;

        .content-phone {
          position: relative;
          .username {
            position: absolute;
            z-index: 999;
            left: 10px;
            top: 0;
            display: flex;
            line-height: 40px;
            img {
              display: block;
              background: var(--theme-color);
            }
            span {
              color: #88909f;
              font-size: 16px;
            }
          }
        }
      }
      .email {
        padding: 40px 0 0 0;
        .content-phone {
          position: relative;
          .username {
            position: absolute;
            z-index: 999;
            left: 10px;
            top: 0;
            display: flex;
            line-height: 40px;
            img {
              display: block;
              background: var(--theme-color);
            }
            span {
              color: #88909f;
              font-size: 16px;
            }
          }
        }
      }
    }
  }
  .ivu-form-item-error-tip {
    padding-left: 10px;
  }
  .ivu-input {
    height: 40px;
    border-radius: 20px;
    padding: 4px 0px 4px 56px;
    font-size: 16px;
  }
  .ivu-form-item {
      margin-bottom: 24px;
  }
  .van-dialog {
    width: 350px;
    .van-dialog__header {
      width: 350px;
      padding-top: 20px;
      line-height: 1.4;
      font-size: 18px;
    }
    .van-button--large {
      height: 60px;
      font-size: 18px;
      line-height: 60px;
    }
  }
}
</style>
